import {
  nav2
} from '../tools/nav2';
import {
  users
} from '../tools/users';
import {
  localData
} from '~/tools/localData'
import TabMenu from './data';
Component({
  data: {
    active: 0,
    list: TabMenu,
    theme: {
      custom: {
        colorPrimary: '#333',
      },
    },
    newMsgCount: 0,
    cartGoodsNum: 0,
    user: null,
  },
  lifetimes: {
    attached() {
      this.countCartGoodsNum()
    }
  },
  methods: {
    getClipboardComponent() {
      return this.selectComponent('#i-clipboard')
    },
    chatTap(e) {
      // console.log('tab-bar.chatTap')
    },
    onChange(event) { // 切换TabBar
      const active = event.detail.value // new tab index
      this.navigateToTab(active)
    },
    navigateToTab(active) {
      const that = this
      const url = (active == 2 ? "pages/home/home" : this.data.list[active].url)
      wx.switchTab({ // 注意：每个页面的 this.getTabBar() 对象是不同的
        url: url.startsWith('/') ? url : `/${url}`,
        success: (res) => {
          const topPage = getCurrentPages()[0]
          if (url.indexOf('pages/home/home') >= 0) {
            topPage.loadGoodsList && topPage.loadGoodsList(true, active == 2 ? 'ticket' : 'home')
          } else if (url.indexOf('pages/usercenter/index') >= 0 && that.data.newMsgCount > 0) { // click person center
            // topPage.nav2Chat && topPage.nav2Chat()
          }
          topPage.getTabBar().countCartGoodsNum()
        }
      });
    },
    init(index) {
      this.initChat()
      this.activate(index)
    },
    activate(index) {
      this.setData({
        active: index
      })
    },
    initChat() {
      const ichat = this.selectComponent('#i-chat')
      ichat?.refresh && ichat.refresh()
      users.getUserInfo().then(user => {
        this.setData({
          user,
          chatTarget: ['admin', 'master'].indexOf(user.role) >= 0 ? 'list' : 'self'
        })
      })
    },
    countCartGoodsNum() {
      let cartGoodsNum = 0
      localData.get('cart')?.forEach && localData.get('cart')?.forEach(ele => {
        cartGoodsNum += (ele.cartNum || ele.minNum || 1)
      });
      this.setData({
        cartGoodsNum
      })
    },
    getCartTabPosition() {
      return new Promise((resolve, reject) => {
        const query = this.createSelectorQuery();
        query.select('#cart').boundingClientRect(res => {
          if (res) {
            resolve({
              left: res.left,
              top: res.top
            }); // 返回Tab的坐标
          } else {
            reject('未找到购物车Tab节点');
          }
        }).exec();
      });
    }
  }
});